package com.example.flutter_demo2.aty

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LifecycleOwner
import com.example.flutter_demo2.MyApplication.Companion.fragmentEngineName
import com.example.flutter_demo2.contants.Pages
import com.example.flutter_demo2.plugins.router.FlutterRouterObserver
import com.example.flutter_demo2.plugins.router.RouteCallback
import io.flutter.embedding.android.FlutterView
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.plugin.platform.PlatformPlugin
import java.util.*
import kotlin.collections.HashMap

class HostActivity : AppCompatActivity(), RouteCallback {

    companion object {
        fun actionStart(context: Context) {
            context.startActivity(Intent(context, HostActivity::class.java))
        }
    }

    private lateinit var flutterView: FlutterView
    private lateinit var flutterEngine: FlutterEngine

    // 宿主activity记录flutter的路由栈信息
    private val mFlutterRouteStack: Stack<String> by lazy {
        Stack()
    }

    override fun onCreate(savedInstanceState: Bundle?) {

        // 这里flutter栈也复用了，flutter侧的回退和android侧的回退都需要注意特殊处理
        // 左上角返回只控制flutter侧的返回，虚拟按键返回只控制原生activity的返回，需要合并处理，最好都在flutter侧处理
        // 方案是native侧做监听，在宿主activity用成员变量存储flutter侧栈信息，flutter侧回退到最后一栈与native一同退出
        // 具体实现见demo，可以使用BasicMessageChannel，在初始化引擎时一同初始化channel
        flutterEngine = FlutterEngineCache.getInstance().get(fragmentEngineName)!!
        FlutterRouterObserver.addHostCallback(this)
        flutterEngine.navigationChannel.pushRoute(Pages.testPageRoute)

        // 固定写法：预先让engine进入resume状态，防止白屏过渡页
        flutterEngine.lifecycleChannel.appIsResumed()

        super.onCreate(savedInstanceState)
        // 固定写法：适配flutter沉浸式状态栏
        configureStatusBarForFullscreenFlutterExperience()
        flutterView = FlutterView(applicationContext)
        flutterView.attachToFlutterEngine(flutterEngine)
        setContentView(flutterView)
    }

    override fun onResume() {
        super.onResume()
        flutterEngine.lifecycleChannel.appIsResumed()
    }

    override fun onPause() {
        super.onPause()
        flutterEngine.lifecycleChannel.appIsPaused()
    }

    override fun onDestroy() {
        super.onDestroy()
        flutterView.detachFromFlutterEngine()
    }

    private fun configureStatusBarForFullscreenFlutterExperience() {
        val window = window
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.statusBarColor = 0x00000000
        window.decorView.systemUiVisibility = PlatformPlugin.DEFAULT_SYSTEM_UI
    }

    override fun onBackPressed() {
        if (mFlutterRouteStack.size <= 1) {
            super.onBackPressed()
            flutterEngine.navigationChannel.popRoute()
        } else {
            flutterEngine.navigationChannel.popRoute()
        }
    }

    @Synchronized
    override fun onPush(route: String) {
        mFlutterRouteStack.push(route)
    }

    @Synchronized
    override fun onPop(route: String) {
        mFlutterRouteStack.pop()
        if (mFlutterRouteStack.isEmpty() && !isFinishing) {
            finish()
        }
    }

    @Synchronized
    override fun onReplace(newRoute: String, oldRoute: String) {
        mFlutterRouteStack.pop()
        mFlutterRouteStack.push(newRoute)
    }

    override fun onRemove(route: String) {
        // no use for temp
    }

    override fun routeNative(nativeRoute: String, params: HashMap<String, Any>?) {
        // no use for temp
    }

    override fun getLifecycleOwner(): LifecycleOwner {
        return this
    }

}